package com.yima.baseproj.module.sys.menu;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yima.baseproj.config.exception.type.ApiException;
import com.yima.baseproj.module.sys.menu.model.MenuAddOrEditModel;
import com.yima.baseproj.module.sys.role.SysRoleService;
import com.yima.baseproj.module.sys.role.menu.SysRoleMenuEntity;
import com.yima.baseproj.module.sys.role.menu.SysRoleMenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SysMenuService extends ServiceImpl<SysMenuMapper, SysMenuEntity> {

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysRoleService sysRoleService;

    public List<String> findAllPerByUserId(String userId) {
        if("1".equals(userId)){
            List<SysMenuEntity> sysMenuEntityList = baseMapper.selectList(Wrappers.<SysMenuEntity>query().eq("type","GONGNENG"));
            return sysMenuEntityList.stream().map(SysMenuEntity::getPermission).collect(Collectors.toList());
        }else{
            return baseMapper.selectPermissionByUserId(userId);
        }
    }

    public List<MenuAddOrEditModel> findUserMenuByTree(String userId) {
        if (userId.equals("1")) {
            return baseMapper.selectMenu("0");
        } else {
            //根据用户id查询所有角色
            List<String> roleIdList = sysRoleService.selectIdByUserId(userId);
            //查询所有菜单
            List<SysRoleMenuEntity> roleMenuEntityList = sysRoleMenuService.list(Wrappers.<SysRoleMenuEntity>query().in("role_id",roleIdList));
            //补全所有菜单
            List<SysMenuEntity> menuEntityList = baseMapper.selectList(Wrappers.<SysMenuEntity>query().eq("is_show",1).in("id",roleMenuEntityList.stream().map(SysRoleMenuEntity::getMenuId).collect(Collectors.toList())));
            String levelStrIds = menuEntityList.stream().map(SysMenuEntity::getLevelStr).collect(Collectors.joining(","));
            List<String> levelStrIdList = Arrays.asList(levelStrIds.split(","));

            List<SysMenuEntity> menuAllList = baseMapper.selectBatchIds(levelStrIdList);
            List<MenuAddOrEditModel> list = BeanUtil.copyToList(menuAllList, MenuAddOrEditModel.class);
            List<MenuAddOrEditModel> caidanList = list.stream().filter(item->"0".equals(item.getPid())).sorted(Comparator.comparing(MenuAddOrEditModel::getSort)).collect(Collectors.toList());
            for (MenuAddOrEditModel caidanModel : caidanList) {
                List<MenuAddOrEditModel> zicaidanList = list.stream().filter(item->caidanModel.getId().equals(item.getPid())).sorted(Comparator.comparing(MenuAddOrEditModel::getSort)).collect(Collectors.toList());
                caidanModel.setChildren(zicaidanList);
            }
            return caidanList;
        }
    }

    public String[] getAllPer(){
        Set<String> set = CollectionUtil.newHashSet();

        List<SysMenuEntity> list = list();
        list.stream().forEach(item->{
            if(StringUtils.isNotBlank(item.getPermission())){
                set.add(item.getPermission());
            }
        });

        return set.toArray(new String[set.size()]);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delById(String id) {
        removeById(id);
        sysRoleMenuService.deleteByRoleId(id);
    }

    public String getMenuLevelStr(String pid, String id) {
        if("0".equals(pid)){
            return CollUtil.join(Arrays.asList("0",id),",");
        }else{
            SysMenuEntity pSysMenuEntity = baseMapper.selectById(pid);
            if(pSysMenuEntity == null){
                throw ApiException.getInstance("父级不存在,请刷新重试");
            }
            return CollUtil.join(Arrays.asList(pSysMenuEntity.getLevelStr(),id),",");
        }
    }
}